#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-10 下午2:43
from threading import Lock
from werkzeug.wsgi import pop_path_info, peek_path_info


class PathDispatcher(object):
    def __init__(self, default_app, create_app):
        super(PathDispatcher, self).__init__()
        self.default_app = default_app
        self.create_app = create_app
        self.lock = Lock()
        self.instances = {}

    def get_application(self, prefix):
        if prefix == 'default':
            return None

        with self.lock:
            app = self.instances.get(prefix)
            if app is None:
                app = self.create_app(prefix)
                if app is not None:
                    self.instances[prefix] = app
            return app

    def __call__(self, environ, start_response):
        # 获取到第一个path，比如http://127.0.0.1:8080/pad/abc
        # 返回pad
        prefix = peek_path_info(environ)
        print 'prefix:', prefix
        app = self.get_application(prefix)
        if app is not None:
            # 弹出pad
            print pop_path_info(environ)
        else:
            app = self.default_app
        return app(environ, start_response)